package com.lin.missyou.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.model.User;
import com.lin.missyou.repository.UserRepository;
import com.lin.missyou.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author gcq
 * @Create 2021-10-29
 */
@Service
public class WxAuthenticationService {

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private UserRepository userRepository;

    @Value("${wx.code2session}")
    private String code2SessionUrl;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;

    /**
     * MessageFormat 模板字符串 解析 {} 中对应的值
     * 1、获取微信openId流程
     *      获取微信小程序给到的code
     *      向微信服务器发送请求，获取当前用户唯一的openId
     * 2、生成jwt
     * @param code
     * @return
     */
    public String code2Session(String code)
    {
        Map<String, Object> session = new HashMap<>();
        String url = MessageFormat.format(this.code2SessionUrl, this.appid, this.appsecret, code);
        RestTemplate rest = new RestTemplate();
        String sessionText = rest.getForObject(url, String.class);
        try {
            session = mapper.readValue(sessionText, Map.class);
            // 容错处理
            //  1、没有获取到，写一条日志
            //  2、很多地方都需要容错处理
            //  3、对每一个错误码做出处理，有很多。
            //  4、能够处理的进行处理下。不断完善
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return this.registerUser(session);
    }

    private String registerUser(Map<String, Object> session)
    {
        String openId = (String)session.get("openid");
        if(openId == null)
        {
            throw new ParameterException(20004);
        }
        Optional<User> userOptional = userRepository.findByOpenid(openId);
        // 如果有值的话
        if(userOptional.isPresent())
        {
            // TODO 返回JWT令牌
            return JwtToken.makeToken(userOptional.get().getId());
        }
        User user = User.builder().openid(openId).build();
        userRepository.save(user);
        Long uid = user.getId();
        // 返回JWT令牌
        return JwtToken.makeToken(uid);
    }
}